﻿<MudDataGrid @ref="_dataGrid"
             Items="@_fruits"
             Filterable="true"
             Hideable="true"
             Groupable="true"
             GroupExpanded="false">
    <ToolBarContent>
        <MudText Typo="Typo.h6">Fruits</MudText>
        <MudSpacer />
    </ToolBarContent>
    <Columns>
        <PropertyColumn Property="x => x.Name" Title="Name" Filterable="false" Groupable="false" />
        <PropertyColumn Property="x => x.Category" Title="Category" Grouping="true" GroupBy="@_groupBy">
            <GroupTemplate>
                <span style="font-weight:bold">Category: @context.Grouping.Key</span>
            </GroupTemplate>
        </PropertyColumn>
    </Columns>
</MudDataGrid>

<div class="d-flex flex-wrap mt-4">
    <MudButton Class="expand-all" OnClick="@ExpandAllGroups" Color="@Color.Primary">Expand All</MudButton>
    <MudButton OnClick="@CollapseAllGroups" Color="@Color.Primary">Collapse All</MudButton>
    <MudButton OnClick="@RefreshList" Color="@Color.Primary">Refresh</MudButton>
</div>

@code {
    private MudDataGrid<TestObject> _dataGrid = null!;

    private IEnumerable<TestObject> _fruits =
        new List<TestObject>
        {
            new TestObject("1", "1"),
            new TestObject("1-1", "1"),
            new TestObject("1-2", "1"),

            new TestObject("2", "2"),
            new TestObject("2-1", "2"),
            new TestObject("2-2", "2"),

            new TestObject("3", "3"),
            new TestObject("3-1", "3"),
            new TestObject("3-2", "3")
        };

    private readonly Func<TestObject, object> _groupBy = x => x.Category;

	public void RefreshList()
	{
		_fruits = _fruits.Select(x => new TestObject(x.Name, x.Category)).ToList();
	}

	public Task ExpandAllGroups()
	{
		return _dataGrid.ExpandAllGroupsAsync();
	}

	public Task CollapseAllGroups()
	{
		return _dataGrid.CollapseAllGroupsAsync();
	}

    public record TestObject(string Name, string Category);
}
